package com.kanche.bigbaby.support.listview;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;

/**
 * Created by Chenshao_Young on 15/5/18.
 */
public class PullLoadListView extends android.support.v7.widget.RecyclerView {

    Context context;
    LinearLayoutManager linearLayoutManager;
    int lastVisibleItem = 0;
    SampleAdapter adapter;
    IPullLoadListener loadListener;

    @Override
    public SampleAdapter getAdapter() {
        return adapter;
    }

    public void setAdapter(SampleAdapter adapter) {
        this.adapter = adapter;
//        setAdapter(this.adapter);
    }

    public IPullLoadListener getLoadListener() {
        return loadListener;
    }

    public void setLoadListener(IPullLoadListener loadListener) {
        this.loadListener = loadListener;
    }

    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
//                    Toast.makeText(MainActivity.this, "DOWN", 0).show();
//                    mSwipeRefreshWidget.setRefreshing(false);

                    adapter.getList().clear();
//                    addList();
                    break;
                case 1:
//                    Toast.makeText(MainActivity.this, "UP", 0).show();
//                    addList();
                    break;
                default:
                    break;
            }

        }

    };

    OnScrollListener scrollListener = new OnScrollListener() {
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
            if (newState == RecyclerView.SCROLL_STATE_IDLE && lastVisibleItem + 1 == adapter.getItemCount()) {
//                handler.sendEmptyMessageDelayed(1, 3000);
                loadListener.loadMore();
            }
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition();
        }
    };

    public PullLoadListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        this.linearLayoutManager = new LinearLayoutManager(this.context);

        init();
    }

    public PullLoadListView(Context context) {
        this(context, null);
    }

    void init(){
        setOnScrollListener(scrollListener);
        setLayoutManager(linearLayoutManager);
        setItemAnimator(new DefaultItemAnimator());
        setHasFixedSize(true);
    }

    public interface IPullLoadListener{

        void loadMore();
    }


}
